# coding: utf-8
"""
2020/12/21 11:14:00  lizr  v1.0
"""
import os
import sys
import time
import shutil
import shelve
import hashlib
from datetime import datetime
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QFileDialog, QStatusBar, QSystemTrayIcon, QMenu
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtGui import QTextCursor, QIcon
from mian import Ui_MainWindow


class MainWin(QMainWindow):
    trg_file_path = ''
    org_file_path = ''

    def __init__(self):
        super().__init__()
        self.setup_ui()

    def setup_ui(self):
        """

        :return:
        """
        # 初始化主UI
        self.main_ui = Ui_MainWindow()
        self.main_ui.setupUi(self)
        # 选择原目录
        self.main_ui.but_org_path.clicked.connect(self.but_org_path)
        # 选择目标目录
        self.main_ui.but_trg_path.clicked.connect(self.but_trg_path)

        # 运行
        self.main_ui.but_run.clicked.connect(self.run)

        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)

        # 初始化线程
        self.file_sync = FileSyncTh()
        self.file_sync.setTerminationEnabled(True)
        self.file_sync.log.connect(self.out_log)
        self.file_sync.status.connect(self.status_bar.showMessage)

        # 加载配置文件
        self.load_conf()

    def pbMin(self):
        """
        添加右键菜单
        :return:
        """
        m = QMenu()
        m.addAction('暂停')
        m.addAction('退出')
        m.triggered.connect(lambda x: print(x.text()))
        self.hide()
        self.mSysTrayIcon = QSystemTrayIcon(self)
        icon = QIcon("img/logo.png")
        self.mSysTrayIcon.setIcon(icon)
        self.mSysTrayIcon.setToolTip("我在这里哦！")
        self.mSysTrayIcon.activated.connect(self.onActivated)
        self.mSysTrayIcon.setContextMenu(m)
        self.mSysTrayIcon.show()

    def onActivated(self, reason):
        if reason == self.mSysTrayIcon.Trigger:
            self.show()
            self.showNormal()
            self.mSysTrayIcon.hide()

    def changeEvent(self, event):
        if event.type().__str__() == 'PySide2.QtCore.QEvent.Type.WindowStateChange':
            print('窗口事件')
            if self.isMinimized():
                self.pbMin()
                print('最小化')
            elif self.isMaximized():
                print("窗口最大化")
            elif self.isFullScreen():
                print("全屏显示")
            elif self.isActiveWindow():
                print("活动窗口")

    def save_conf(self):
        """
        保存配置
        :return:
        """
        with shelve.open(r'data', writeback=True) as f:
            data = {'org_path': self.org_file_path, 'trg_path': self.trg_file_path,
                    'sl': int(self.main_ui.spin_sleep.text()), 'file_type': self.main_ui.line_file_type.text(),
                    'dirs': self.main_ui.line_dirs.text()}
            f.update(data)

    def load_conf(self):
        """
        加载配置
        :return:
        """
        with shelve.open(r'data', writeback=True) as f:
            if f:
                org_path = f.get('org_path', '')
                self.main_ui.line_org_path.setText(org_path)
                self.org_file_path = org_path
                trg_path = f.get('trg_path', '')
                self.main_ui.line_trg_path.setText(trg_path)
                self.trg_file_path = trg_path
                sl = f.get('sl', 30)
                self.main_ui.spin_sleep.setValue(int(sl))
                file_type = f.get('file_type', '')
                self.main_ui.line_file_type.setText(file_type)
                dirs = f.get('dirs', '')
                self.main_ui.line_dirs.setText(dirs)
            else:
                self.main_ui.spin_sleep.setValue(300)

    def out_log(self, s):
        """
        日志输出
        :param s:
        :return:
        """
        self.main_ui.log_out.append(s)
        self.main_ui.log_out.moveCursor(QTextCursor.End)

    def but_trg_path(self):
        """
        选择目标目录
        :return:
        """
        self.main_ui.line_trg_path.clear()
        self.trg_file_path = QFileDialog.getExistingDirectory(self)
        self.main_ui.line_trg_path.setText(self.trg_file_path)

    def but_org_path(self):
        """
        选择原目录
        :return:
        """
        self.main_ui.line_org_path.clear()
        self.org_file_path = QFileDialog.getExistingDirectory(self)
        self.main_ui.line_org_path.setText(self.org_file_path)

    def run(self):
        """
        启动
        :return:
        """
        but_txt = self.main_ui.but_run.text()
        sleep = int(self.main_ui.spin_sleep.text())
        if not self.org_file_path or not self.trg_file_path:
            return QMessageBox.warning(self, '警告', '请选择源目录/目标目录', QMessageBox.Yes)

        # 检查源目录 跟 目标目录是否一致，如果一致者不允许同步
        if self.org_file_path == self.trg_file_path:
            return QMessageBox.warning(self, '警告', '原目录不允许跟目标目录一致', QMessageBox.Yes)

        # 保存配置
        self.save_conf()

        # 备份文件
        if but_txt == '启动':
            self.file_sync.trg_file_path = self.trg_file_path
            self.file_sync.org_file_path = self.org_file_path
            self.file_sync.st = 1
            self.file_sync.sleep = sleep
            self.file_sync.file_type = self.main_ui.line_file_type.text()
            self.file_sync.dirs = self.main_ui.line_dirs.text()
            self.main_ui.but_run.setText('暂停')
            self.file_sync.start()
        else:

            self.file_sync.st = 0
            self.file_sync.sleep = 1
            self.main_ui.but_run.setText('启动')
            self.file_sync.terminate()
            print('结束')


class FileSyncTh(QThread):
    log = pyqtSignal(str)
    status = pyqtSignal(str)
    trg_file_path = ''
    org_file_path = ''
    file_type = ''
    dirs = ''
    sleep = 1
    st = 0

    def __init__(self):
        super().__init__()

    def run(self):
        while True:
            if self.st == 1:
                # 获取源目录所有文件路径
                rate = 0
                ts_t = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
                try:
                    files = self.get_org_files_path(self.org_file_path, [])
                    files = [i for i in files if self.exten_filter(i)]  # 过滤文件类型
                    files = [i for i in files if self.dirs_filter(i)]  # 排除文件夹
                    for file in files:
                        rate += 1
                        per = round(rate / len(files) * 100, 2)  # 百分比
                        self.status.emit(f'{per}% 完成, 当前文件{file}')
                        trg_file = '/'.join([self.trg_file_path, str(file).replace(self.org_file_path + '/', '')])
                        # print(file)
                        # print(trg_file)
                        gett = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
                        # 如果文件不存在
                        if not os.path.exists(trg_file):
                            # 创建目录
                            os.makedirs(trg_file.rsplit('/', 1)[0], exist_ok=True)
                            shutil.copy(file, trg_file)
                            msg = '新增'
                            self.log.emit(f'{gett}--{msg}--{trg_file}')
                        # 文件存在
                        else:
                            # md5校验文件
                            if self.md5sum(file) != self.md5sum(trg_file):
                                print('md5 不一样')
                                shutil.copy(file, trg_file)
                                msg = '更新'
                                self.log.emit(f'{gett}--{msg}--{trg_file}')
                            else:
                                msg = '最新'
                except Exception as e:
                    with open(r'log.log', 'w', encoding='utf-8') as f:
                        f.write(f'{ts_t}-{e}\n')
                    input('程序已报错，请把log.log反馈给开发者，开发者邮箱：m.go@qq.com')
                    break

            time.sleep(self.sleep)

    def exten_filter(self, file):
        """
        扩展名过滤
        :return:
        """

        exten = str(self.file_type).split('|')
        if not exten:
            return True
        if not exten[0]:
            return True
        kzm = str(file).rsplit('.', 1)[-1]
        if kzm in exten:
            return True
        return False

    def dirs_filter(self, file):
        """
        文件夹过滤
        :return:
        """
        exten = [str(i).replace('\\', '/').strip() for i in str(self.dirs).split('|') if i]
        # print(exten)
        if not exten:
            return True
        if not exten[0]:
            return True
        dir_path = str(file).rsplit('/', 1)[0]  # 获取目录路径
        # print(dir_path)
        for i in exten:
            if i in dir_path:
                return False
        return True

    def md5sum(self, filename):
        """
        文件校验
        :param filename:
        :return:
        """
        size = os.path.getsize(filename)
        cdate = os.path.getatime(filename)
        file_md5 = hashlib.md5((str(cdate) + str(size)).encode('utf-8'))
        return file_md5.hexdigest()

    def get_org_files_path(self, file_path, org_files_path: list):
        """
        获取原目录所有文件路径
        :return:
        """
        files = os.listdir(file_path)
        for file in files:
            new_path = '/'.join([file_path, file])
            if os.path.isdir(new_path):
                self.get_org_files_path(new_path, org_files_path)
            else:
                self.status.emit(f'索引文件中....{new_path}')
                org_files_path.append(new_path)
        return org_files_path


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_win = MainWin()
    main_win.show()
    sys.exit(app.exec_())
